#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>       
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <net/if.h>

#include "thr_channel.h"
#include "thr_list.h"
#include "proto.h"

#define THRNUM    3
#define DEFAULT_DEVICES "wlan0"
int sd;

struct sockaddr_in raddr;
int main()
{

    int i,err;    
	int num[2][2]={{1,2},{3,5}};
	pthread_t  tid[THRNUM];
	sd = socket(AF_INET,SOCK_DGRAM,0);

	if(sd < 0)
	{
		perror("socket()");
		exit(1);
	}


	struct ip_mreqn mreq;
	inet_pton(AF_INET,DEFAULT_MGROUP,&mreq.imr_multiaddr);  
	inet_pton(AF_INET,"0.0.0.0",&mreq.imr_address);
	mreq.imr_ifindex = if_nametoindex(DEFAULT_DEVICES); //  获得索引号;

	if(setsockopt(sd,IPPROTO_IP,IP_MULTICAST_IF,&mreq,sizeof(mreq)) < 0)
	{
		perror("setsockopt()");
		exit(1);
	}

	raddr.sin_family = AF_INET;
	raddr.sin_port = htons(atoi(DEFAULT_RCVPORT));
	inet_pton(AF_INET,DEFAULT_MGROUP,&raddr.sin_addr);

	// 创建chanl线程
	// 创建list线程
	for(i = 0;i < THRNUM;i++)
	{
		if(i == 0)
		{
			err = pthread_create(tid+i,NULL,thr_list_create,NULL);
			if(err)
			{
				fprintf(stderr,"pthread_create():%s\n",strerror(err));
				exit(1);
			}                                                              
		}

		else
		{

			err = pthread_create(tid+i,NULL,thr_channel_create,(void *)&num[i-1]);
			if(err)
			{
				fprintf(stderr,"thr_channel_create():%s\n",strerror(err));
				exit(1);
			}
		}

	}

	// 销毁线程
	for(i = 0;i < THRNUM;i++) {
		pthread_join(tid[i],NULL);
	}
	exit(0);
}
